package com.ynny.service;

import com.ynny.bean.Book;
import com.ynny.bean.User;
import com.ynny.dao.BookDao;
import com.ynny.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class BookServiceImpl02 implements BookService {
    @Autowired
    BookDao bookDao;
    @Autowired
    UserDao userDao;

    @Transactional
    @Override
    public int buyBook(Integer userId, Integer bookId) {
        //1.查询图书价格
        // 1.2 查询图书是否存在
        Book book = bookDao.selectBookById(bookId);
        if (book == null){

            //-1 图书不存在
            return -1;
        }
        //图书价格
        Integer price = book.getPrice();
        //2.修改图书库存
        if (book == null){
            //图书不存在
            return -2;
        }
        //2.2 判断库存是否足够
        Integer stock = book.getStock();
        if (stock < 1){
            //库存不足
            return -3;
        }
        int i = bookDao.updateBookStock(bookId);

        if (i != 1){
            // 服务器异常 库存修改失败
            return -4;
        }

        //3.修改用户余额
        //3.1查询用户是否存在
        User user = userDao.selectUserById(userId);
        if (user == null){
            //用户不存在
            return -5;
        }
        //3.2 判断余额是否足够
        Integer balance = user.getBalance();
        if (balance < price){
            //余额不足
            return -6;
        }
        //3.3 修改余额
        int j = userDao.updateUserBalance(userId, price);

        if (j != 1){
            //服务器异常 余额修改失败
            return -7;
        }
        return 1;
    }
}
